// use base64::{Engine as _, engine::general_purpose};

use std::io;
use std::io::{Read, Write};
use std::path::Path;

use base64::engine::general_purpose;
use base64::Engine;

//字符串转base64
//base64解码为字符串

//url base64
#[test]
fn test1() {
    let ori_data = String::from("data");
    //let ori_data_bytes = b"data";
    let encoded: String = general_purpose::STANDARD_NO_PAD.encode(ori_data.as_bytes());

    println!(">>>{} 的 base64：{}", ori_data, encoded);

    let e_ori_data = &general_purpose::STANDARD_NO_PAD.decode(encoded).unwrap(); //解码
    println!(">>>>{:?}", e_ori_data);
    let dd: String = e_ori_data.iter().map(|d| *d as char).collect(); //解码字节流转字符串
    println!("{}", dd);

    // or, URL-safe
    let orig = b"https://www.baidu.com/s?ie=utf-8&f=3&rsv_bp=1&tn=baidu&wd=crates.io&oq=crate.rs&rsv_pq=9dfe674a0023a286&rsv_t=17ebd3wuXGBkZJVHpL2lv%2FVxsm4T0hyy%2Bv6KWKAhmQ4djpEaAT0vY4fvDog";
    let encoded_url = general_purpose::URL_SAFE_NO_PAD.encode(orig);
    println!(">>>url encoded: {}", encoded_url);
}

//文件转base64
#[test]
fn test2() {
    let path = Path::new("C:\\Users\\HG11\\Desktop\\test.txt");
    if path.exists() {
        let encoded = file_to_base64(path.to_str().unwrap());
        println!("{}", encoded);
    } else {
        println!("文件不存在");
    }
}

//base64转文件
#[test]
fn test3() {
    let file_base64 = "Me+8jOaXpeWOhuOAgeaXtumSn+OAgeiuoeeul+WZqOOAgeinhumikeaSreaUvuWZqOOAgeW9lemfs+acuuOAgemfs+S5kO+8jOWbvuW6k+OAgemAmuiur+W9leOAgXNlYXJjaO+8jOWIoOaOiei/meS6m+S4jeebuOWFs+ezu+e7n+W6lOeUqC0tLeWPr+S7peWunueOsA0KMu+8jOemgeeUqOmUruebmEYxLUYxMuOAgWhvbWXjgIFmbuOAgVByaW50IFNjcmVlbu+8iOaIquWxj+aMiemUru+8ieOAgeS8keecoC0tLeS4jeS4gOWumuiDveWunueOsA0KNO+8jOmihOijheezu+e7n+mcg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new("C:\\Users\\HG11\\Desktop\\test_aa.txt");
    let file_path = "C:\\Users\\HG11\\Desktop\\test_aa_ddd.txt";
    base64_to_file(file_path, file_base64).expect("base64转文件失败")
}

/// 将文件转为base64字符串
fn file_to_base64(file_path: &str) -> String {
    // 打开文件
    let mut file = std::fs::File::open(file_path).unwrap();
    // 创建一个空的向量以存储文件内容
    let mut contents = Vec::new();
    // 将文件内容读入向量
    file.read_to_end(&mut contents).unwrap();
    // 将向量内容进行Base64编码
    let encoded = general_purpose::STANDARD_NO_PAD.encode(&contents);
    // 返回编码后的结果
    return encoded;
}

/// 将文件base64字符串转成file
fn base64_to_file(file_path: &str, base64_str: &str) -> io::Result<()> {
    // 将base64字符串解码
    let decoded = general_purpose::STANDARD_NO_PAD.decode(base64_str).unwrap();
    // 创建文件并写入解码后的数据
    let mut file = std::fs::File::create(file_path).unwrap();
    file.write_all(&decoded).unwrap();
    // 返回操作成功的结果
    Ok(())
}
